package com.zhq.blog.manage.domain.controller.user;

import javax.validation.Valid;

import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zhq.blog.core.domain.user.Sale;
import com.zhq.blog.manage.domain.controller.BaseController;
import com.zhq.blog.manage.domain.controller.BossModel;

@Controller
@Scope("prototype")
@RequestMapping("/admin/user/sale/*")
public class SaleController extends BaseController {
	
	@RequestMapping()
    public BossModel index(String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable){
		if(viewState == null || viewState.equals("")){
			return createModel("admin/user/sale/list").add("salesPage",context.getSaleRepository().findAll(pageable)).add("viewState", "");

		}else{
			return createModel("admin/user/sale/list").add("salesPage",context.getSaleRepository().findAll(pageable)).add("viewState", viewState);
		}
	}
	@RequestMapping(value="edit/{id}")
	public BossModel edit(@PathVariable long id){
		return createModel("admin/user/sale/info").add("sale",context.getSaleRepository().findOne(id));
	}
	
	@RequestMapping(value="add")
	public BossModel add(){
		return createPrizeModel(new Sale());
	}
	
	@RequestMapping(value="save",method = RequestMethod.POST)
	public BossModel save(@Valid final Sale sale, final BindingResult bindingResult, final ModelMap model, RedirectAttributes redirectSales,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable){
		if (bindingResult.hasErrors()) {
			return createModel("admin/user/sale/info");
		}
		context.getSaleRepository().save(sale);
		String message = sale.getSucessFlashMessage();
		redirectSales.addFlashAttribute("message", message);
		return createModel("redirect:/admin/user/sale/index");
		
	}
	
	@RequestMapping(value="delete",method= RequestMethod.POST)
	public BossModel delete(String viewState,long id,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable){
		context.getSaleRepository().delete(id);
		return createModel("admin/user/sale/sale_table").add("salesPage",context.getSaleRepository().findAll(pageable)).add("viewState", viewState);
	}
	
	private BossModel createPrizeModel(Sale sale){
		BossModel modelAndView = createModel("admin/user/sale/info");
		if(sale != null)
			modelAndView.add("sale",sale);
		return modelAndView;
	}

}
